/**
 * BaiduAPI.java
 * Created at 2017-3-26
 * Created by xieshuang
 * Copyright (C) 2017 BROADTEXT SOFTWARE, All rights reserved.
 */
package com.broadtext.common.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.lang3.StringUtils;

/**
 * <p>
 * ClassName: BaiduAPI
 * </p>
 * <p>
 * Description: 百度地图api
 * </p>
 * <p>
 * Author: xieshuang
 * </p>
 * <p>
 * Date: 2017-3-26
 * </p>
 */
public class BaiduAPI {
    private static String ak = "IPMbrnKDsTtd6OsIISlQU5blv5Gn6vtq";
    
    static double pi = 3.14159265358979324;
    static double a = 6378245.0;
    static double ee = 0.00669342162296594323;
    public final static double x_pi = 3.14159265358979324 * 3000.0 / 180.0;

    public static double[] wgs2bd(double lat, double lon) {
           double[] wgs2gcj = wgs2gcj(lat, lon);
           double[] gcj2bd = gcj2bd(wgs2gcj[0], wgs2gcj[1]);
           return gcj2bd;
    }

    /**
     * 
     * <p>Description: GCJ坐标转换为百度坐标</p>
     * @param lat
     * @param lon
     * @return
     */
    public static double[] gcj2bd(double lat, double lon) {
           double x = lon, y = lat;
           double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
           double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
           double bd_lon = z * Math.cos(theta) + 0.0065;
           double bd_lat = z * Math.sin(theta) + 0.006;
           return new double[] { bd_lat, bd_lon };
    }

    public static double[] bd2gcj(double lat, double lon) {
           double x = lon - 0.0065, y = lat - 0.006;
           double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
           double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
           double gg_lon = z * Math.cos(theta);
           double gg_lat = z * Math.sin(theta);
           return new double[] { gg_lat, gg_lon };
    }

    /**
     * 
     * <p>Description: WGS坐标转换为GCJ坐标。</p>
     * @param lat
     * @param lon
     * @return
     */
    public static double[] wgs2gcj(double lat, double lon) {
           double dLat = transformLat(lon - 105.0, lat - 35.0);
           double dLon = transformLon(lon - 105.0, lat - 35.0);
           double radLat = lat / 180.0 * pi;
           double magic = Math.sin(radLat);
           magic = 1 - ee * magic * magic;
           double sqrtMagic = Math.sqrt(magic);
           dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * pi);
           dLon = (dLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * pi);
           double mgLat = lat + dLat;
           double mgLon = lon + dLon;
           double[] loc = { mgLat, mgLon };
           return loc;
    }

    private static double transformLat(double lat, double lon) {
           double ret = -100.0 + 2.0 * lat + 3.0 * lon + 0.2 * lon * lon + 0.1 * lat * lon + 0.2 * Math.sqrt(Math.abs(lat));
           ret += (20.0 * Math.sin(6.0 * lat * pi) + 20.0 * Math.sin(2.0 * lat * pi)) * 2.0 / 3.0;
           ret += (20.0 * Math.sin(lon * pi) + 40.0 * Math.sin(lon / 3.0 * pi)) * 2.0 / 3.0;
           ret += (160.0 * Math.sin(lon / 12.0 * pi) + 320 * Math.sin(lon * pi  / 30.0)) * 2.0 / 3.0;
           return ret;
    }

    private static double transformLon(double lat, double lon) {
           double ret = 300.0 + lat + 2.0 * lon + 0.1 * lat * lat + 0.1 * lat * lon + 0.1 * Math.sqrt(Math.abs(lat));
           ret += (20.0 * Math.sin(6.0 * lat * pi) + 20.0 * Math.sin(2.0 * lat * pi)) * 2.0 / 3.0;
           ret += (20.0 * Math.sin(lat * pi) + 40.0 * Math.sin(lat / 3.0 * pi)) * 2.0 / 3.0;
           ret += (150.0 * Math.sin(lat / 12.0 * pi) + 300.0 * Math.sin(lat / 30.0 * pi)) * 2.0 / 3.0;
           return ret;
    }

    /**
     * 
     * <p>
     * Description: 根据经纬度调用百度api解析地理位置
     * </p>
     * 
     * @param lat 纬度
     * @param lon 经度
     * @return 地理位置
     * @throws IOException 异常
     */
    public static String DecodeLonLat(double lat, double lon) throws IOException {
        URL url = new URL("http://api.map.baidu.com/geocoder?" + ak + "&callback=renderReverse&location=" + lat
                + "," + lon + "&output=json");
        URLConnection connection = url.openConnection();
        /**
         * 然后把连接设为输出模式。URLConnection通常作为输入来使用，比如下载一个Web页。
         * 通过把URLConnection设为输出，你可以把数据向你个Web页传送。下面是如何做：
         */
        connection.setDoOutput(true);
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "utf-8");
        //        remember to clean up
        out.flush();
        out.close();
        //        一旦发送成功，用以下方法就可以得到服务器的回应：
        String res;
        InputStream l_urlStream;
        l_urlStream = connection.getInputStream();
        BufferedReader in = new BufferedReader(new InputStreamReader(l_urlStream, "UTF-8"));
        StringBuilder sb = new StringBuilder("");
        while ((res = in.readLine()) != null) {
            sb.append(res.trim());
        }
        String str = sb.toString();
        if (StringUtils.isNotEmpty(str)) {
            int addStart = str.indexOf("formatted_address\":");
            int addEnd = str.indexOf("\",\"business");
            if (addStart > 0 && addEnd > 0) {
                String address = str.substring(addStart + 20, addEnd);
                return address;
            }
        }
        return "";

    }
}
